﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;

namespace DeskMoe;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private const string SaveFilePath = "notes.txt";
    private NotifyIcon? notifyIcon;
    private const int HOTKEY_ID = 1;
    private const uint MOD_CONTROL = 0x0002;
    private const uint MOD_ALT = 0x0001;
    private const uint VK_N = 0x4E;

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    public MainWindow()
    {
        InitializeComponent();
        LoadNotes();
        SetupNotifyIcon();
    }

    private void SetupNotifyIcon()
    {
        try
        {
            notifyIcon = new NotifyIcon();
            notifyIcon.Text = "桌萌记";
            notifyIcon.Visible = true;
            notifyIcon.DoubleClick += (s, e) => ShowWindow();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"系统托盘图标初始化失败：{ex.Message}", "错误");
        }
    }

    private void SetupHotKey()
    {
        var helper = new WindowInteropHelper(this);
        RegisterHotKey(helper.Handle, HOTKEY_ID, MOD_CONTROL | MOD_ALT, VK_N);
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        var source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
        source?.AddHook(HwndHook);
        SetupHotKey();
    }

    private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        const int WM_HOTKEY = 0x0312;
        if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID)
        {
            ShowWindow();
            handled = true;
        }
        return IntPtr.Zero;
    }

    private void ShowWindow()
    {
        Show();
        Activate();
    }

    private void LoadNotes()
    {
        try
        {
            if (File.Exists(SaveFilePath))
            {
                txtContent.Text = File.ReadAllText(SaveFilePath);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载笔记失败：{ex.Message}", "错误");
        }
    }

    private void SaveNotes()
    {
        try
        {
            File.WriteAllText(SaveFilePath, txtContent.Text);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"保存笔记失败：{ex.Message}", "错误");
        }
    }

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        SaveNotes();
        MessageBox.Show("保存成功！", "提示");
    }

    private void btnClear_Click(object sender, RoutedEventArgs e)
    {
        if (MessageBox.Show("确定要清空内容吗？", "确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
        {
            txtContent.Clear();
        }
    }

    private void btnHide_Click(object sender, RoutedEventArgs e)
    {
        Hide();
    }

    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        SaveNotes();
        var helper = new WindowInteropHelper(this);
        UnregisterHotKey(helper.Handle, HOTKEY_ID);
        notifyIcon?.Dispose();
        base.OnClosing(e);
    }
}